package com.go.where.family.api.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.go.where.family.api.constants.Constant;
import com.go.where.family.api.scoket.Head;
import com.go.where.family.api.scoket.SocketDTO;
import com.go.where.family.api.scoket.TransmissionCode;
import com.go.where.family.api.server.HttpServerStartMain;
import com.go.where.family.api.utils.CommonUtil;
import com.go.where.family.api.utils.IpUtil;
import com.go.where.family.api.utils.MD5Util;
import com.go.where.family.api.utils.ServletUtil;
import com.go.where.family.api.vo.CustomerAddressVo;
import com.go.where.family.api.vo.UserResultVo;
import com.google.gson.Gson;

/**
 * 上传客户地址
 * 
 * @description
 * @author
 * @date
 */
public class UploadAddressServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(UploadAddressServlet.class);
	private static Gson gson = CommonUtil.gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.
	 * HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		//
		String address = req.getParameter("address");
		String consignee = req.getParameter("consignee");
		String postcode = req.getParameter("postcode");
		String customerId = req.getParameter("customerId");
		String region = req.getParameter("region");
		String mobile = req.getParameter("mobile");
		// 校验密文
		String sign = req.getParameter("sign");

		log.info("上传客户地址：address：" + address + ",consignee：" + consignee
				+ ",postcode：" + postcode + ",customerId：" + customerId
				+ ",region：" + region + ",mobile：" + mobile + ",sign：" + sign);
		boolean check = super.checkUser(req, resp);
		if (!check) {
			return;
		}
		boolean flag = this.validateData(address, consignee, customerId,
				region, mobile, sign, resp, req);
		if (flag) {// 数据校验成功
			try {
				CustomerAddressVo vo = new CustomerAddressVo();
				vo.setCustomerId(customerId);
				vo.setMobile(mobile);
				vo.setConsignee(consignee);
				vo.setAddress(address);
				vo.setPostcode(postcode);
				vo.setRegion(region);
				SocketDTO dto = sendMessage(vo, req);
				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				// String resMsg = head.getResponseMessage();
				String body = dto.getBody();
				if (TransmissionCode.SUCCESS.getCode().equals(resCode)) {
					// 把service中返回的信息转成对应的json格式字符串，返回给接口调用者
					if (StringUtils.isNotBlank(body)) {
						boolean res = gson.fromJson(body, Boolean.class);
						if (res) {
							UserResultVo ri = new UserResultVo();
							ri.setCode(Constant.SUCCESS);
							ri.setStatus(Constant.TRUE);
							ServletUtil.writeResJsonStr(resp, CommonUtil.gson()
									.toJson(ri));
						} else {
							ServletUtil.writeErrorStr(resp);
						}
					} else {
						ServletUtil.writeErrorStr(resp);
					}
				} else {
					log.error("内部通信异常，" + head.getResponseMessage());
					ServletUtil.writeErrorStr(resp);
				}
			} catch (Exception e) {
				log.error("异常信息", e);
				// 异常情况，也把对应异常信息的json格式字符串返回给接口调用者
				ServletUtil.writeErrorStr(resp);
			}
		}
	}

	/**
	 * 向service服务发送请求
	 * 
	 * @param t
	 * @param req
	 * @return
	 */
	private SocketDTO sendMessage(CustomerAddressVo vo, HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.SAVE_ADDRESS);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("api");
		return super.send(head, vo);
	}

	/**
	 * 数据校验合法性
	 * 
	 * @param id
	 * @param sign
	 * @param resp
	 * @param req
	 * @return
	 * @throws IOException
	 */
	private boolean validateData(String address, String consignee,
			String customerId, String region, String mobile, String sign,
			HttpServletResponse resp, HttpServletRequest req)
			throws IOException {
		UserResultVo ri = new UserResultVo();
		boolean result = false;
		if (StringUtils.isEmpty(sign)) {
			log.info("签名字符串为空!!!");
			ri.setCode(Constant.SIGN_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else if (StringUtils.isEmpty(address)) {
			log.info("收货地址为空!!!");
			ri.setCode(Constant.ADDRESS_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else if (StringUtils.isEmpty(consignee)) {
			log.info("收货人为空为空!!!");
			ri.setCode(Constant.CONSIGNEE_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
			// } else if (StringUtils.isEmpty(region)) {
			// log.info("收货地区为空!!!");
			// ri.setCode(Constant.REGION_IS_NULL);
			// ri.setStatus(Constant.FALSE);
			// ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			// return false;
		} else if (StringUtils.isEmpty(mobile)) {
			log.info("客户手机号码为空!!!");
			ri.setCode(Constant.CUSTOMER_MOBILE_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else {
			String key = HttpServerStartMain.getValue("go.where.family.key");
			StringBuilder builder = new StringBuilder();
			builder.append("address");
			builder.append(address);
			builder.append("consignee");
			builder.append(consignee);
			builder.append("customerId");
			builder.append(customerId);
			builder.append("mobile");
			builder.append(mobile);
			if (StringUtils.isNotBlank(region)) {
				builder.append("region");
				builder.append(region);
			}
			builder.append("key");
			builder.append(key);

			String data = builder.toString();

			boolean checked = MD5Util.checkMD5Signature(data, sign);
			if (checked) {
				result = true;
			} else {
				log.info("数字签名失败！！！");
				ri.setCode(Constant.CHECK_SIGN_FAIL);
				ri.setStatus(Constant.FALSE);
				ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
				return false;
			}
		}

		return result;
	}
}
